package best.driver.android.manager;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.*;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import best.driver.android.*;
import best.driver.android.Activity.Environment.DownLoadApkActivity;
import best.driver.android.Beans.AppVersionInfo;
import best.driver.android.Event.DownloadApkEvent;
import best.driver.android.Event.UploadFileEvent;
import best.driver.android.Service.BestService;
import best.driver.android.Utils.FileUtils;
import best.driver.android.Utils.Logger;
import best.driver.android.Utils.NotificationUtils;
import best.driver.android.Utils.UIThreadUtil;
import best.driver.android.View.ConfirmDialog;
import best.driver.android.View.ConfirmDialogListener;
import best.driver.android.View.DialogDismissListener;
import best.driver.android.View.HintDialog;
import best.driver.android.common.app.AppProxyFactory;
import best.driver.android.common.network.ApiObjectRequest;
import best.driver.android.common.network.ApiRequest;
import best.driver.android.common.network.BestError;
import de.greenrobot.event.EventBus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

import java.io.*;

public class UpgradeManager {

    private static UpgradeManager instance = null;

    public static final String ACTION_HEADER = "cn.best.android.UpgradeManager";
    public static final String ACTION_SHOW_NOTIFY = "cn.best.android.UpgradeManager.ACTION_SHOW_NOTIFY";
    public static final String ACTION_SHOW_DOWNLOAD = "cn.best.android.UpgradeManager.ACTION_SHOW_DOWNLOAD";
    public static final String ACTION_SHOW_INSTALL = "cn.best.android.UpgradeManager.ACTION_SHOW_INSTALL";
    public static final String ACTION_CLEAR_CACHE = "cn.best.android.UpgradeManager.ACTION_CLEAR_CACHE";

    private static final String SYNC_DOWNLOADING_KEY = "SYNC_DOWNLOADING_KEY";
    private static final String SYNC_GET_INSTANCE_KEY = "SYNC_GET_INSTANCE_KEY";

    private static final String PRE_KEY_UPGRADE_MANAGER = "best.PRE_KEY_UPGRADE_MANAGER";
    private static final String PRE_CURRENT_VERSION = "best.PRE_KEY_UPGRADE_MANAGER.PRE_CURRENT_VERSION";
    private static final String PRE_FILE_LENGTH = "best.PRE_KEY_UPGRADE_MANAGER.PRE_FILE_LENGTH";
    private static final String PRE_DOWNLOAD_URL = "best.PRE_KEY_UPGRADE_MANAGER.PRE_DOWNLOAD_URL";
    private static final String PRE_HAS_DOWNLOADING = "best.PRE_KEY_UPGRADE_MANAGER.PRE_HAS_DOWNLOADING";

    public static final String INTENT_KEY_NEW_VERSION = "newVersion";
    public static final String INTENT_KEY_DOWNLOAD_URL = "downloadUrl";

    private Context context;
    private boolean downloading = false;
    private boolean autoInstall = false;
    private boolean receiverRegistered = false;

    public static String theLatestVersion;


    public final static int dontUpgrade = 0;
    public final static int isForceUpgrade = 1;
    public final static int isAdviceUpgrade = 2;

    private SharedPreferences preferences;
    private String currentVersion;
    private long fileLength;
    private String downloadUrl;

    private File file;
    private HttpClient httpClient;
    private HttpGet httpGet;
    private BufferedInputStream inputStream = null;
    private BufferedOutputStream outputStream = null;

    private NotificationManager notifiManager;
    private Notification updateProcessNotification;
    private static final int UPGRADE_NOTIFICATION_ID = R.string.app_name;

    RemoteViews updateView;

    private BroadcastReceiver networkStatusReceiver;

    private UpgradeManager(Context context) {
        this.context = context;

        preferences = context.getSharedPreferences(PRE_KEY_UPGRADE_MANAGER, Context.MODE_PRIVATE);
        initParams();
        initFile();
        notifiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    private void initParams() {
        currentVersion = preferences.getString(PRE_CURRENT_VERSION, "");
        fileLength = preferences.getLong(PRE_FILE_LENGTH, 0);
        downloadUrl = preferences.getString(PRE_DOWNLOAD_URL, "");
    }

    private void initFile() {
        if (null == file) {
            File dir = new File(FileUtils.getBaseDataDir(context), FileUtils.BASE_FOLDER_NAME);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            file = new File(dir, "upgrade.apk");
            try {
                if (!file.exists()) {
                    file.createNewFile();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static UpgradeManager getInstance(Context context) {
        synchronized (SYNC_GET_INSTANCE_KEY) {
            if (null == instance) {
                instance = new UpgradeManager(context);
            }
            return instance;
        }
    }

    public void onHandleIntent(Intent intent) {

        String action = intent.getAction();

        if (ACTION_CLEAR_CACHE.equals(action)) {
            clearData();
            return;
        }

        String newVersion = intent.getStringExtra(INTENT_KEY_NEW_VERSION);
        String url = intent.getStringExtra(INTENT_KEY_DOWNLOAD_URL);

        if (!currentVersion.equals(newVersion) || !url.equals(downloadUrl)) {
            clearData();
            setParams(newVersion, 0, url);
        }

        if (ACTION_SHOW_DOWNLOAD.equals(action)) {
            showDownloading(true);
        } else if (ACTION_SHOW_NOTIFY.equals(action)) {
            if (getHasDownloadingFlag()) {
                showDownloading(false);
            } else {
                showHasNew();
            }
        } else if (ACTION_SHOW_INSTALL.equals(action)) {
            install();
        }
    }

    /**
     * 通知有新版本时显示相应的NOTIFY
     */
    private void showHasNew() {

        Notification notification = new Notification();
        //notification.icon = R.drawable.small_icon;
        notification.tickerText = context.getString(R.string.app_name);
        notification.when = System.currentTimeMillis();
        notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;
        Intent intent = new Intent(context, BestService.class);
        intent.setAction(ACTION_SHOW_DOWNLOAD);
        intent.putExtra(INTENT_KEY_NEW_VERSION, currentVersion);
        intent.putExtra(INTENT_KEY_DOWNLOAD_URL, downloadUrl);
        PendingIntent pendingIntent = PendingIntent.getService(context, (int) System.currentTimeMillis(), intent, 0);
        notification.contentIntent = pendingIntent;
        notification.contentView = NotificationUtils.createMsgNotificationView(context, context.getString(R.string.app_name),"");

        notifiManager.notify(UPGRADE_NOTIFICATION_ID, notification);
    }

    /**
     * 正在下载时显示相应的NOTIFY
     */
    private void showDownloading(final boolean autoInstall) {

        this.autoInstall = autoInstall;

        if (getDownloadedLength() == fileLength && fileLength != 0) {
            if (autoInstall) {
                install();
            }
            showCompleted();

            Intent intentDownLoadFinish = new Intent();
            intentDownLoadFinish
                    .setAction(AppConstant.BROADCAST_ACTION_DOWNLOADFINISH);
            BestApp.getInstance().sendBroadcast(intentDownLoadFinish);

            return;
        }

        if (null == updateProcessNotification) {
            updateProcessNotification = new Notification();
            //updateProcessNotification.icon = R.drawable.small_icon;
            updateProcessNotification.tickerText = context.getString(R.string.app_name);
            updateProcessNotification.defaults = Notification.DEFAULT_LIGHTS;

            // 设置任务栏中下载进程显示的views
            updateView = new RemoteViews(context.getPackageName(), R.layout.notification_download);
            updateView.setTextViewText(R.id.update_id_tvProcess,
                    String.format(context.getString(R.string.download_process), 0));
            updateView.setProgressBar(R.id.update_id_pbDownload, 100, 0, false);
            updateProcessNotification.contentView = updateView;

            PendingIntent pi = PendingIntent.getService(context, (int) System.currentTimeMillis(), new Intent(context,
                    BestService.class), PendingIntent.FLAG_UPDATE_CURRENT);
            updateProcessNotification.contentIntent = pi;
        }
        notifiManager.notify(UPGRADE_NOTIFICATION_ID, updateProcessNotification);
        beginDownload(autoInstall);
    }

    /**
     * 下载完成时显示相应的NOTIFY
     */
    private void showCompleted() {

        Notification completeNotification = new Notification();
        //completeNotification.icon = R.drawable.small_icon;
        completeNotification.tickerText = "";
        completeNotification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;

        // 设置任务栏中下载进程显示的views
        RemoteViews completeView = new RemoteViews(context.getPackageName(), R.layout.notification_download);
        completeView.setTextViewText(R.id.update_id_tvProcess,
                String.format(context.getString(R.string.download_completed), 0));
        completeView.setTextViewText(R.id.update_id_tvProcess,
                String.format(context.getString(R.string.download_process), 100));
        completeView.setTextViewText(R.id.update_id_tvDescription, context.getString(R.string.download_completed));
        completeView.setProgressBar(R.id.update_id_pbDownload, 100, 100, false);
        completeNotification.contentView = completeView;

        Intent intent = new Intent(context, BestService.class);
        intent.setAction(ACTION_SHOW_INSTALL);
        intent.putExtra(INTENT_KEY_NEW_VERSION, currentVersion);
        intent.putExtra(INTENT_KEY_DOWNLOAD_URL, downloadUrl);

        PendingIntent pi = PendingIntent.getService(context, (int) System.currentTimeMillis(), intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        completeNotification.contentIntent = pi;
        notifiManager.notify(UPGRADE_NOTIFICATION_ID, completeNotification);
    }

    /**
     * 下载失败时显示相应的NOTIFY
     */
    private void showFailed() {
//        Notification notification = new Notification();
//        //notification.icon = R.drawable.small_icon;
//        notification.tickerText = "下载失败";
//        notification.when = System.currentTimeMillis();
//        notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;
//        notification.contentView = NotificationUtils.createMsgNotificationView(context,
//                "下载失败","");
//        Intent intent = new Intent(context, BestService.class);
//        intent.setAction(ACTION_SHOW_DOWNLOAD);
//        intent.putExtra(INTENT_KEY_NEW_VERSION, currentVersion);
//        intent.putExtra(INTENT_KEY_DOWNLOAD_URL, downloadUrl);
//        PendingIntent pendingIntent = PendingIntent.getService(context, (int) System.currentTimeMillis(), intent, 0);
//        notification.contentIntent = pendingIntent;
//
//        notifiManager.notify(UPGRADE_NOTIFICATION_ID, notification);
    }

    /**
     * 更新进度
     */
    private void updateProgress(int downloadPercent) {
//        updateView.setTextViewText(R.id.update_id_tvProcess,
//                String.format(context.getString(R.string.download_process), downloadPercent));
//        updateView.setProgressBar(R.id.update_id_pbDownload, 100, downloadPercent, false);
//        updateProcessNotification.contentView = updateView;
//        updateProcessNotification.defaults = Notification.DEFAULT_LIGHTS;
//
//        notifiManager.notify(UPGRADE_NOTIFICATION_ID, updateProcessNotification);
    }

    private void beginDownload(final boolean autoInstall) {

        synchronized (SYNC_DOWNLOADING_KEY) {
            if (downloading) {
                return;
            }
            downloading = true;
        }
        registerReceiver();
        setHasDownloadingFlag(true);
        download(downloadUrl, autoInstall);
    }

    private void download(String url, final boolean autoInstall) {

        url = "http://pkg.fir.im/70b46b5ebf12bbab22490304f72f36e93e2ca0da.apk?attname=%E8%B4%A7%E4%B8%BB%E7%AB%AF_1106.apk_1.0.2.apk&e=1447211521&token=LOvmia8oXF4xnLh0IdH05XMYpH6ENHNpARlmPc-T:5D6n_jNGYBjWi2cPQAYfOeL87eg=";
        try {
            if (!file.exists()) {
                file.createNewFile();
            }

            url = url.trim();

            long downloadedLength = getDownloadedLength();

            BasicHttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, 10 * 1000);
            HttpConnectionParams.setSoTimeout(httpParameters, 10 * 1000);

            httpClient = new DefaultHttpClient(httpParameters);
            httpGet = new HttpGet(url);
            httpGet.addHeader("Range", "bytes=" + downloadedLength + "-");

            Logger.d("UPGRADE", "url:" + url);
            HttpResponse response;
            try {
                response = httpClient.execute(httpGet);
            } catch (Exception e) {
                Logger.d("UPGRADE", "e:" + e.toString());
                throw e;
            }
            HttpEntity entity = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            if (code != 200 && code != 206) {
                showFailed();
                return;
            }
            long contentLength = entity.getContentLength();

            if (downloadedLength == 0) {
                setParams(currentVersion, contentLength, downloadUrl);
            }

            // 如果与上次记录的文件长度不合，清除数据重新开始下载
            if (fileLength != contentLength + downloadedLength) {
                release();
                if (file.exists()) {
                    file.delete();
                }
                download(url, autoInstall);
                return;
            }

            InputStream contentStream = entity.getContent();
            if (contentStream != null) {

                inputStream = new BufferedInputStream(contentStream);
                outputStream = new BufferedOutputStream(new FileOutputStream(file, true));

                int len = -1;
                long wroteLength = 0;
                byte[] buffer = new byte[1024];
                int prePercent = (int) (downloadedLength / (double) fileLength * 100);
                prePercent = 0;
                while ((len = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, len);
                    wroteLength += len;

                    final int percent = (int) (wroteLength / (double) fileLength * 100);
                    Logger.d("download_length", wroteLength + "");
                    Logger.d("download_percent", percent + "");

                    // 每下载完成1%就通知任务栏进行修改下载进度
                    if (percent - prePercent >= 1) {
                        prePercent = percent;
                        UIThreadUtil.run(new Runnable() {
                            @Override
                            public void run() {
                                updateProgress(percent);
                                DownloadApkEvent event = new DownloadApkEvent();
                                event.process = percent;
                                EventBus.getDefault().post(event);
                                Logger.d("percent: ", percent +"");
                            }
                        });
                        Intent intentProgress = new Intent();
                        intentProgress
                                .setAction(AppConstant.BROADCAST_ACTION_PROGRESS);
                        intentProgress
                                .putExtra(AppConstant.EXTRA_progress, percent);
                        BestApp.getInstance().sendBroadcast(intentProgress);
                    }
                }
                outputStream.flush();

                Intent intentDownLoadFinish = new Intent();
                intentDownLoadFinish
                        .setAction(AppConstant.BROADCAST_ACTION_DOWNLOADFINISH);
                BestApp.getInstance().sendBroadcast(intentDownLoadFinish);

                UIThreadUtil.run(new Runnable() {
                    @Override
                    public void run() {
                        unregisterReceiver();
                        if (autoInstall) {
                            install();
                        }
                        showCompleted();


                        // notifiManager.cancel(AppInfo.NOTIFICATION_ID);
                    }
                });

            }

        } catch (Exception e) {
            e.printStackTrace();

            Intent intentDownLoadErro = new Intent();
            intentDownLoadErro.setAction(AppConstant.BROADCAST_ACTION_DOWNLOADERRO);
            BestApp.getInstance().sendBroadcast(intentDownLoadErro);

            showFailed();
        } finally {
            synchronized (SYNC_DOWNLOADING_KEY) {
                this.downloading = false;
            }
            release();
        }

    }

    private void registerReceiver() {
        if (receiverRegistered) {
            return;
        }
        receiverRegistered = true;
        if (networkStatusReceiver == null) {
            networkStatusReceiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context arg0, Intent intent) {
                    boolean isBreak = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
                    if (downloading) {
                        if (isBreak) {
                            release();
                            showFailed();
                        } else {
                            beginDownload(autoInstall);
                        }

                    }
                }
            };
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.setPriority(1000);
        context.registerReceiver(networkStatusReceiver, filter);
    }

    private void unregisterReceiver() {
        if (!receiverRegistered) {
            return;
        }
        if (networkStatusReceiver != null) {
            context.unregisterReceiver(networkStatusReceiver);
        }
    }

    private void release() {

        try {
            if (inputStream != null) {
                inputStream.close();
                inputStream = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if (outputStream != null) {
                outputStream.close();
                outputStream = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (httpGet != null) {
            httpGet.abort();
            httpGet = null;
        }

        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
    }

    private void setParams(String currentVersion, long fileLength, String url) {
        this.currentVersion = currentVersion == null ? "" : currentVersion;
        this.fileLength = fileLength;
        this.downloadUrl = url == null ? "" : url;

        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(PRE_CURRENT_VERSION, this.currentVersion);
        editor.putString(PRE_DOWNLOAD_URL, this.downloadUrl);
        editor.putLong(PRE_FILE_LENGTH, fileLength);
        editor.commit();
    }

    private boolean getHasDownloadingFlag() {
        return preferences.getBoolean(PRE_HAS_DOWNLOADING, false);
    }

    private void setHasDownloadingFlag(boolean hasDownloading) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(PRE_HAS_DOWNLOADING, hasDownloading);
        editor.commit();
    }

    private void clearData() {
        if (file.exists()) {
            file.delete();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        setParams("", 0, "");
        setHasDownloadingFlag(false);
    }

    private long getDownloadedLength() {
        if (file.exists()) {
            return file.length();
        }
        return 0L;
    }

    private void install() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    // ----以上部分由后台Service调用-----以下部分由前台应用调用----


    /**
     * 检测版本，获取版本升级信息
     */
    public static void reqCheckVersion() {
        ApiObjectRequest<AppVersionInfo> request = RequestFactory.createGetVersionRequest(AppConfig.APP_VERSION, false, "Android");
        request.setListener(new ApiRequest.ApiRequestListener<AppVersionInfo>() {
            @Override
            public void onRequestSuccess(AppVersionInfo response) {
                if(response.newVersionFlag) {
                    UpgradeManager.getInstance(BestApp.getInstance()).showNewVersionDialog(response, BestApp.getInstance());
                }
            }

            @Override
            public void onRequestError(BestError error) {

            }
        });
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
    }

    /**
     * 检测版本，并显示相应 notify
     */
    public void checkAndNotify(final Context context) {

        ApiObjectRequest<AppVersionInfo> request = RequestFactory.createGetVersionRequest(AppConfig.APP_VERSION, false, "Android");
        request.setListener(new ApiRequest.ApiRequestListener<AppVersionInfo>() {
            @Override
            public void onRequestSuccess(AppVersionInfo response) {
                response.newVersionFlag = true;
                AppConstant.sApkSize = 4064578;
                fileLength = 4064578;
                if(response.newVersionFlag) {
                    UpgradeManager.getInstance(BestApp.getInstance()).showNewVersionDialog(response, context);
                }
            }

            @Override
            public void onRequestError(BestError error) {
                int a = 8;
            }
        });
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
    }

    public void hasUpperVersion(final Context context,
                                       AppVersionInfo item) {
        if (item.forceUpdateFlag) {// 强制升级
            notifyForcedUpdate(context, item);
        } else {// 建议升级
            notifyHasNew(context, item);
        }
    }

    private void notifyNoUpdate(Context context) {
        Intent intent = new Intent(ACTION_CLEAR_CACHE);
        intent.setClass(context, BestService.class);
        context.startService(intent);
    }

    private void notifyHasNew(Context context, AppVersionInfo upgradeInfo) {

        Intent intent = new Intent(ACTION_SHOW_DOWNLOAD);
        intent.setClass(context, BestService.class);
        //intent.putExtra(INTENT_KEY_NEW_VERSION, upgradeInfo.latestVersion);
        //intent.putExtra(INTENT_KEY_DOWNLOAD_URL, upgradeInfo.packageUrl);
        context.startService(intent);
    }

    public void notifyForcedUpdate(final Context context, final AppVersionInfo upgradeInfo) {
        Intent intent = new Intent(ACTION_SHOW_DOWNLOAD);
        intent.setClass(context, BestService.class);
        //intent.putExtra(INTENT_KEY_NEW_VERSION, upgradeInfo.latestVersion);

        intent.putExtra(INTENT_KEY_DOWNLOAD_URL, "http://pkg.fir.im/70b46b5ebf12bbab22490304f72f36e93e2ca0da.apk?attname=%E8%B4%A7%E4%B8%BB%E7%AB%AF_1106.apk_1.0.2.apk&e=1447211521&token=LOvmia8oXF4xnLh0IdH05XMYpH6ENHNpARlmPc-T:5D6n_jNGYBjWi2cPQAYfOeL87eg=");
        context.startService(intent);

        Intent intentStartDownload = new Intent();
        intentStartDownload.setAction(AppConstant.BROADCAST_ACTION_STARTDOWNLOAD);
        context.sendBroadcast(intentStartDownload);

    }

    public String getAppVersion() {
        try {
            PackageManager packageManager = BestApp.getInstance().getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(BestApp.getInstance().getPackageName(), 0);
            String version = packInfo.versionName;
            return version;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "0.8.0";
    }

//    public static Boolean isHaveNewVersion() {
//        if (theLatestVersion != null) {
//            if (isNewVersion(getAppVersion(), theLatestVersion)) {
//                return true;
//            } else {
//                return false;
//            }
//        } else {
//            return false;
//        }
//    }


//    private static boolean isNewVersion(String client, String server) {
//        Log.e("client,server", client + "  " + server);
//        boolean result = false;
//        try {
//            String[] ori = client.split("\\.");
//            for (String temp : ori) {
//                Log.e("temp", temp);
//            }
//            String[] tar = server.split("\\.");
//            if (ori.length == 3) {
//                client = client + ".0";
//                ori = client.split("\\.");
//            }
//            if (tar.length == 3) {
//                server = server + ".0";
//                tar = server.split("\\.");
//            }
//
//            int len = tar.length;
//
//            for (int i = 0; i < len; i++) {
//                if (Integer.valueOf(ori[i]) > Integer.valueOf(tar[i])) {
//                    return false;
//                }
//                if (Integer.valueOf(ori[i]) < Integer.valueOf(tar[i])) {
//                    return true;
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return result;
//    }

    public void showNewVersionDialog(final AppVersionInfo item, final Context context) {
        if(BestApp.getInstance().getLastActivity() == null) {
            return;
        }
        final ConfirmDialog dialog = new ConfirmDialog(BestApp.getInstance().getLastActivity(), "");
        dialog.setTitle("发现新版本");
        dialog.setContent(item.forceUpdateFlag ? "您的版本过低无法使用" : "v" + item.version);
        dialog.ad.setCancelable(item.forceUpdateFlag);

        dialog.setListener(new ConfirmDialogListener() {
            @Override
            public void onClickConfirm() {
                if(BestApp.getInstance().getLastActivity() != null) {
                    BestApp.getInstance().getLastActivity().startActivity(new Intent(BestApp.getInstance().getLastActivity(), DownLoadApkActivity.class));
                }
                hasUpperVersion(BestApp.getInstance(), item);
//                download("http://pkg.fir.im/70b46b5ebf12bbab22490304f72f36e93e2ca0da.apk?attname=%E8%B4%A7%E4%B8%BB%E7%AB%AF_1106.apk_1.0.2.apk&e=1447211521&token=LOvmia8oXF4xnLh0IdH05XMYpH6ENHNpARlmPc-T:5D6n_jNGYBjWi2cPQAYfOeL87eg=", true);
//                dialog.dismiss();
            }
        });

        dialog.setDismissListener(new DialogDismissListener() {
            @Override
            public void onDismiss() {
                if (item.forceUpdateFlag) {
                    BestApp.getInstance().exit();
                }
                //dialog.dismiss();
            }
        });

    }

}
